package com.info33.platform.common.huawei;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.ocr.v1.OcrClient;
import com.huaweicloud.sdk.ocr.v1.model.IdCardRequestBody;
import com.huaweicloud.sdk.ocr.v1.model.IdCardResult;
import com.huaweicloud.sdk.ocr.v1.model.IdcardVerificationResult;
import com.huaweicloud.sdk.ocr.v1.model.RecognizeIdCardRequest;
import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
import com.info33.platform.common.exception.ResultException;
import org.springframework.util.ObjectUtils;

/**
 * @author debj
 * @version 1.0
 * @date 2021/10/12 18:27
 */
public class HuaWeiApi {

    private HuaWeiApi() {
    }

    /**
     * 身份证图片 base64 码进行识别
     *
     * @param image 身份证图片 base64 码
     * @return 三方 api 响应体
     */
    public static IdCardResult idCardWithImage(String image) {
        return idCardWithImage(image, "front", Boolean.TRUE);
    }

    /**
     * 身份证图片 base64 码进行识别
     *
     * @param image              身份证图片 base64 码
     * @param side               front/身份证正面、back/身份证背面。（如果参数值为空或无该参数,系统自动识别,建议填写,准确率更高）
     * @param returnVerification 是否返回校验身份证号等信息，default false
     * @return 三方 api 响应体
     */
    public static IdCardResult idCardWithImage(String image, String side, Boolean returnVerification) {
        IdCardRequestBody body = new IdCardRequestBody();
        body.withReturnVerification(returnVerification);
        body.withSide(side);
        body.withImage(image);
        return idCard(body);
    }

    /**
     * 身份证图片公网地址进行识别
     *
     * @param url 身份证图片公网路径
     * @return 三方 api 响应体
     * @deprecated 身份证照片暴露公网，不合适
     */
    @Deprecated
    public static IdCardResult idCardWithUrl(String url) {
        return idCardWithUrl(url, "front", Boolean.TRUE);
    }

    /**
     * 身份证图片公网地址进行识别
     *
     * @param url                身份证图片公网地址
     * @param side               front/身份证正面、back/身份证背面。（如果参数值为空或无该参数,系统自动识别,建议填写,准确率更高）
     * @param returnVerification 是否返回校验身份证号等信息，default false
     * @return 三方 api 响应体
     * @deprecated 身份证照片暴露公网，不合适
     */
    @Deprecated
    public static IdCardResult idCardWithUrl(String url, String side, Boolean returnVerification) {
        IdCardRequestBody body = new IdCardRequestBody();
        body.withReturnVerification(returnVerification);
        body.withSide(side);
        body.withUrl(url);
        return idCard(body);
    }

    /**
     * 调用华为身份证识别 api
     *
     * @param body 请求体
     * @return 三方 api 响应体
     */
    private static IdCardResult idCard(IdCardRequestBody body) {
        String ak = "OQZFWLBWNLCGIMEXYNY3";
        String sk = "rBc4OIkynOsXT0RL0ckuGArp0qhqwxiXSsNmQe9l";

        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);

        OcrClient client = OcrClient.newBuilder()
                .withCredential(auth)
                .withRegion(OcrRegion.valueOf("cn-north-4"))
                .build();
        RecognizeIdCardRequest request = new RecognizeIdCardRequest();
        request.withBody(body);
        IdCardResult result = null;
        try {
            result = client.recognizeIdCard(request).getResult();
        } catch (ConnectionException | RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        // 校验是否请求成功
        if (ObjectUtils.isEmpty(result)) {
            throw new ResultException("身份证识别失败，请重试");
        }
        // 校验签证信息是否合法
        if (Boolean.TRUE.equals(body.getReturnVerification())) {
            IdcardVerificationResult check = result.getVerificationResult();
            if (Boolean.FALSE.equals(check.getValidNumber())
                    || Boolean.FALSE.equals(check.getValidBirth())
                    || Boolean.FALSE.equals(check.getValidSex())) {
                throw new ResultException("身份证号信息不合法，请重新识别");
            }
        }
        return result;
    }
}